#!/usr/bin/env bash

# Copyright 2016 The Fuchsia Authors
#
# Use of this source code is governed by a MIT-style
# license that can be found in the LICENSE file or at
# https://opensource.org/licenses/MIT

# This script builds the Zircon toolchain and uploads it to Google Storage.

# This script is expected to be executed on Jenkins, as part of a continuous
# builds infrastructure.  As such, it it organized to accept the arch target
# as an environment variable, since that is how Jenkins passes arguments from
# matrix build configurations.

# This script also assumes a directory structure based on the Zircon Jiri
# manifests.  Jenkins uses these manifests to sync the code.

set -e
set -x

# We assume the following directory structure:
# ./zircon/scripts
# ./third_party/gcc_none_toolchains
readonly SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
cd "${SCRIPT_DIR}/../../third_party/gcc_none_toolchains"

# We require the ARCH variable to be set when calling this script.  Passing arguments
# via environment variables is how Jenkins does things :/
if [[ -z "${ARCH}" ]]; then
  echo "ARCH environment variable must be set!"
  exit 99
fi

# Sanity check the value of ARCH.
if [[ "${ARCH}" != "${ARCH// /}" ]]; then
  echo "ARCH appears to contain spaces; provide only one ARCH at a time"
  exit 99
fi

# Build the toolchain: `do-build` will fetch source, apply patches and build gcc and friends.
./do-build --target "${ARCH}-none" -j2 --strip

# Figure out where the toolchains got generated.  They end up in a directory with the
# structure $ARCH-$ABI-$VERSION-$OS-$HOSTARCH.
readonly OS="$(uname)"
readonly HOSTARCH="$(uname -m)"
readonly ABI="elf"
readonly TOOLCHAIN_DIR="$(ls -td ${ARCH}-${ABI}-*-${OS}-${HOSTARCH} | head -1)"

# Fetch the current git SHA: we upload the prebuilts with a SHA that corresponds
# to the SHA of the tree we built from.
readonly GIT_SHA="$(git log -1 --format=%H)"
readonly TARBALL="/tmp/${GIT_SHA}"

# Write the README file.
cp "${SCRIPT_DIR}/upload-toolchain.README.md" "${TOOLCHAIN_DIR}/README.md"
echo "${GIT_SHA}" >> "${TOOLCHAIN_DIR}/README.md"

# Tar up the toolchain.
tar jcvf "${TARBALL}" "${TOOLCHAIN_DIR}"

# Upload the prebuilts to Google Storage.  We don't do any authentication here because
# we assume that the environment has been set up with auth already.  For notes on
# how to do that, see: https://cloud.google.com/storage/docs/authentication
readonly GS_BUCKET="gs://fuchsia-build/magenta/toolchain/${ARCH}-${ABI}/${OS}-${HOSTARCH}"
gsutil cp "${TARBALL}" "${GS_BUCKET}/${GIT_SHA}"
